package com.ews.onlineexchange.service;

import java.io.IOException;
import java.util.List;

import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.hibernate.search.query.dsl.QueryBuilder;

import com.ews.onlineexchange.model.AgentService;
import com.ews.onlineexchange.model.DataEntity;

@Named
@ConversationScoped
public class FtAgentServiceList extends FullTextEntityQuery<AgentService> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	EjbServiceSupplierHome ejbServiceSupplierHome;
	
	@Override
	public List<AgentService> getResultList() {
		List<AgentService> results = super.getResultList();
		SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<b><font color=\"red\">", "</font></b>");
		QueryScorer qs = new QueryScorer(createLuceneQuery());
		Highlighter highlighter = new Highlighter( formatter, qs);
		Analyzer analyzer = new SmartChineseAnalyzer();
		try {
			for (AgentService dataEntity : results) {
				String findResult = highlighter.getBestFragment(analyzer, getSearchString(), dataEntity.getName());
				if (findResult != null)
					dataEntity.setHighLightTitle(findResult);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidTokenOffsetsException e) {
			e.printStackTrace();
		}
		return results;
	}
	
	@Override
	protected Query createLuceneQuery() {
		String searchQuery = getSearchString();
		FullTextEntityManager ftem = getFullTextEntityManager();
		QueryBuilder agentServiceQb = ftem.getSearchFactory().buildQueryBuilder().forEntity(AgentService.class).get();		
		Query agentServiceQuery = agentServiceQb.keyword().onFields("name").matching(searchQuery).createQuery();

		return agentServiceQuery;
	}

	private String getSearchString() {
		return ejbServiceSupplierHome.getInstance().getMainBusinesses().get(0).getAgentServiceDetail();
	}

	@Override
	protected FullTextQuery createQuery() {
		FullTextEntityManager ftem = getFullTextEntityManager();
		return ftem.createFullTextQuery(createLuceneQuery(), AgentService.class);
	}

}
